package models

import (
	"LoveU/utils"
	"os"
	"path/filepath"
	"strconv"

	"github.com/astaxie/beego"

	"github.com/astaxie/beego/orm"
)

const ALUMB = "alumb/"
const FILENOTFOUND = 202
const FILEEXIST = 203

// 将相册图片URL地址写入到数据库
func WriteToAlumbDB(userid int64, path string) int64 {
	o := orm.NewOrm()
	album := &Album{
		Userid:  userid,
		Picname: path,
	}
	o.Insert(album)
	return 0
}

func WriteToAvatar(userid int64, path string) int64 {
	o := orm.NewOrm()
	qs := o.QueryTable("Pinformation")
	pInfo := new(Pinformation)
	err := qs.Filter("userid", userid).One(pInfo)
	if err != nil {
		return utils.UNKNOWN_ERROR
	}
	pInfo.Avatar = path
	o.Update(pInfo)
	return utils.OK
}

func CheckAlbumURL(userid int64, url string) int64 {
	useridStr := strconv.FormatInt(userid, 10)
	dir, _ := filepath.Abs(filepath.Dir(os.Args[0]))
	beego.Error(dir)
	beego.Error(useridStr)
	beego.Error(ALUMB + useridStr + "/" + url)
	_, err := os.Stat(ALUMB + useridStr + "/" + url)
	if err != nil {
		beego.Error(err.Error())
		return utils.ALBUM_FILE_NOT_EXIST
	}
	return utils.ALBUM_FILE_EXISTS
}

// 获取相册图图片
func GetALBUMList(userid int64) []*Album {
	o := orm.NewOrm()
	qs := o.QueryTable("album")
	albums := make([]*Album, 0)
	_, err := qs.Filter("userid", userid).All(&albums)
	if err != nil {
		return nil
	}
	return albums
}

// 单独获取某用户的头像
func GetUserAvatar(userid int64) string {
	return getUserAvatar(userid)
}

// 获取用户的所有好友之头像
func GetFriendsAvatar(userid int64) map[string]string {
	friends, status := GetFriendsId(userid)
	if status == utils.UNKNOWN_ERROR {
		return nil
	}
	avatarMap := make(map[string]string)
	var avatar string
	for _, friend := range friends {
		info := GetUserInfo(*friend)
		if info == nil {
			avatar = ""
		} else {
			avatar = info.Avatar
		}
		avatarMap[strconv.FormatInt(*friend, 10)] = avatar
	}
	return avatarMap
}
